package com.cci.kangdao.cipFleet.controller;

import com.alibaba.fastjson.JSONObject;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.cipFleet.dto.request.CipFleetAndEsnRequest;
import com.cci.kangdao.cipFleet.dto.request.CipFleetDelRequest;
import com.cci.kangdao.cipFleet.dto.request.CipFleetRequest;
import com.cci.kangdao.cipFleet.dto.response.CipFleetResponse;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.service.impl.SMSEnum;
import com.gexin.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * cip调用车联网车队
 *
 */
@RestController
@RequestMapping("/cipFleet")
@Slf4j
public class CipFleetController {

	@Resource
	private CipFleetService cipFleetService;
	@Resource
	private UserTDao userTDao;
	@Resource
	private DictionariesTDao dictionariesTDao;

	private static final String CIPForeignToken = "cipForeignToken";

	/**
	 * 根据用户查询车辆和车队   此方法已经无逻辑，只是防止以前的调用报错
	 *
	 * @param userId
	 * @return
	 */
	@RequestMapping("/getFleetByUserId.aspx")
	@Deprecated
	public BaseResponse getFleetByUserId(Long userId, @RequestParam(value = "type", defaultValue = "1", required = false) Integer type, @RequestHeader(value = "token") String token) {
		try {
			List<Map<String, Object>> pushTypeLists = dictionariesTDao.getDictionariesListByDTableName(CIPForeignToken);
			boolean success = false;
			if (!CollectionUtils.isEmpty(pushTypeLists) && pushTypeLists.size() > 0) {
				for (Map<String, Object> dict : pushTypeLists) {
					if (dict.get("DValue").equals(token)) {
						success = true;
					}
				}
			}
			if(!success){
				return BaseResponse.error(SMSEnum.type17.getIndex(),"token错误");
			}
			if(null == userId){
				return BaseResponse.error(SMSEnum.type17.getIndex(), "参数不能为空");
			}
			List<CipFleetResponse> list = cipFleetService.getFleetByUserId(userId,type);
			return BaseResponse.success(list);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}

	/**
	 * 根据用户id校验白名单   此方法已经无逻辑，只是防止以前的调用报错
	 * @param userId
	 * @return
	 */
	@RequestMapping("/isFleetWhite.aspx")
	@Deprecated
	public BaseResponse isFleetWhite(Long userId,@RequestHeader(value = "token") String token) {
		try {
			List<Map<String,Object>> pushTypeLists = dictionariesTDao.getDictionariesListByDTableName(CIPForeignToken);
			boolean success = false;
			if(!CollectionUtils.isEmpty(pushTypeLists) && pushTypeLists.size() > 0){
				for(Map<String,Object> dict : pushTypeLists){
					if(dict.get("DValue").equals(token)){
						success = true;
					}
				}
			}
			if(!success){
				return BaseResponse.error(SMSEnum.type17.getIndex(),"token错误");
			}
//			boolean isSuccess = cipFleetService.isFleetWhite(userId);
            return BaseResponse.success(true);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}

	/**
	 * 添加车队信息   此方法已经无逻辑，只是防止以前的调用报错
	 * @param paramStr
	 * @return
	 */
	@RequestMapping(value = "/insertFleet.aspx", method = RequestMethod.POST)
	@Deprecated
	public BaseResponse insertFleet(@RequestBody String paramStr,@RequestHeader(value = "token") String token) {
		List<Map<String,Object>> pushTypeLists = dictionariesTDao.getDictionariesListByDTableName(CIPForeignToken);
		boolean success = false;
		if(!CollectionUtils.isEmpty(pushTypeLists) && pushTypeLists.size() > 0){
			for(Map<String,Object> dict : pushTypeLists){
				if(dict.get("DValue").equals(token)){
					success = true;
				}
			}
		}
		if(!success){
			return BaseResponse.error(SMSEnum.type17.getIndex(),"token错误");
		}
		List<CipFleetRequest> fleetList = JSON.parseArray(paramStr, CipFleetRequest.class);
		for(CipFleetRequest fleet : fleetList){
			UserT user = userTDao.selectById(fleet.getUserId());
			if(null != user){
				fleet.setUserId(user.getId());
			} else {
				return BaseResponse.error(SMSEnum.type17.getIndex(), "用户" + fleet.getUserId() + "不存在");
			}
		}
//		boolean rSuccess = cipFleetService.insertFleet(fleetList);
        return BaseResponse.success(true);
	}


	/**
	 * 删除车队信息----- ---  此方法已经无逻辑，只是防止以前的调用报错
	 * @param paramStr
	 * @return
	 */
	@RequestMapping(value = "/deleteFleet.aspx", method = RequestMethod.POST)
	@Deprecated
	public BaseResponse deleteFleet(@RequestBody String paramStr,@RequestHeader(value = "token") String token) {
		List<Map<String,Object>> pushTypeLists = dictionariesTDao.getDictionariesListByDTableName(CIPForeignToken);
		boolean success = false;
		if(!CollectionUtils.isEmpty(pushTypeLists) && pushTypeLists.size() > 0){
			for(Map<String,Object> dict : pushTypeLists){
				if(dict.get("DValue").equals(token)){
					success = true;
				}
			}
		}
		if(!success){
			return BaseResponse.error(SMSEnum.type17.getIndex(),"token错误");
		}
		List<CipFleetDelRequest> fleetList = JSON.parseArray(paramStr, CipFleetDelRequest.class);
//		boolean isSuccess = cipFleetService.deleteFleet(fleetList);
        return BaseResponse.success(true);
	}


	/**
	 * 根据当前登录用户查询名下车队信息
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping("/appGetFleetList.aspx")
	public BaseResponse appGetFleetList(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer type = 1;
			Long userId = null;
			String externalUserId = null;
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				} else {
					type = this.getType(request);
					externalUserId = this.getHearderUserId(request);
				}
			} else {
				UserT userT = UserThreadLocal.get();
				userId = userT.getId();
			}
			return cipFleetService.appGetFleetList(userId, externalUserId, type);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * app新增车队接口
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping(value = "/appAddFleet.aspx", method = RequestMethod.POST)
	public BaseResponse appAddFleet(@RequestBody String paramStr, HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("appAddFleet接口传参：" + paramStr);
			CipFleetAndEsnRequest cipFleetAndEsnRequest = JSON.parseObject(paramStr, CipFleetAndEsnRequest.class);
			cipFleetAndEsnRequest.setType(1);
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				} else {
					Integer type = this.getType(request);
					cipFleetAndEsnRequest.setType( null != type ? type : 1);
					cipFleetAndEsnRequest.setExternalUserId(this.getHearderUserId(request));
				}
			}
			log.info("appAddFleet接口传参：" + cipFleetAndEsnRequest);
			return cipFleetService.appAddFleet(cipFleetAndEsnRequest);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * 根据当前登陆人id校验车队名称是否存在
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping(value = "/checkFleetName.aspx")
	public BaseResponse checkFleetName(String fleetName, HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer type = 1;
			Long userId = null;
			String externalUserId = null;
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				} else {
					type = this.getType(request);
					externalUserId = this.getHearderUserId(request);
				}
			} else {
				UserT userT = UserThreadLocal.get();
				userId = userT.getId();
			}
			Map<String, Object> returnMap = new HashMap<>();
			int isExist = cipFleetService.checkFleetName(fleetName,type,userId, externalUserId);
			returnMap.put("isExist", isExist);
			return BaseResponse.success(returnMap);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * 获取用户设备列表接口
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping(value = "/appGetEquipmentList.aspx")
	public BaseResponse appGetEquipmentList(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer type = 1;
			Long userId = null;
			String externalUserId = null;
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				} else {
					type = this.getType(request);
					externalUserId = this.getHearderUserId(request);
				}
			} else {
				UserT userT = UserThreadLocal.get();
				if (null != userT) {
					userId = userT.getId();
				}
			}
			return cipFleetService.appGetEquipmentList(userId, externalUserId,type);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * app修改车队接口
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping(value = "/appUpdateFleet.aspx", method = RequestMethod.POST)
	public BaseResponse appUpdateFleet(@RequestBody String paramStr, HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("appUpdateFleet接口传参：" + paramStr);
			CipFleetAndEsnRequest cipFleetAndEsnRequest = JSON.parseObject(paramStr, CipFleetAndEsnRequest.class);
			cipFleetAndEsnRequest.setType(1);
			response.setHeader("Access-Control-Allow-Origin", "*");
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				} else {
					cipFleetAndEsnRequest.setType(this.getType(request));
					cipFleetAndEsnRequest.setExternalUserId(this.getHearderUserId(request));
				}
			}
			log.info("appUpdateFleet接口传参：" + cipFleetAndEsnRequest);
			return cipFleetService.appUpdateFleet(cipFleetAndEsnRequest);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * app删除车队接口
	 * app 端会调用该接口，dcec 老友汇创建车队也会调用
	 *
	 * @return
	 */
	@RequestMapping(value = "/appDeleteFleet.aspx", method = RequestMethod.GET)
	public BaseResponse appDeleteFleet(@RequestParam(value="fleetId",required=false) Long fleetId, @RequestParam(value="cipFleetId",required=false) String cipFleetId,HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			Integer type = 1;
			if (containsTokenAndSource(request)) {
				if (!this.verifyToken(request)) {
					return BaseResponse.error(-99, "获取token信息失败");
				}else {
					type = this.getType(request);
				}
			}
			log.info("appDeleteFleet：fleetId：" + fleetId + ";cipFleetId：" + cipFleetId);
			return cipFleetService.appDeleteFleet(fleetId,cipFleetId,type);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}

	public String getHearderUserId(HttpServletRequest request) {
		String userid = request.getHeader("userid");
		return userid;
	}

	public boolean containsTokenAndSource(HttpServletRequest request) {
		String token = request.getHeader("token");
		String source = request.getHeader("source");
		return StringUtils.isNotBlank(token) && StringUtils.isNotBlank(source);
	}

	public boolean verifyToken(HttpServletRequest request) {
		String token = request.getHeader("token");
		String source = request.getHeader("source");
		//验证token
		String externalFleet = dictionariesTDao.getListByDTableName("ExternalFleet");
		List<JSONObject> jsonObjectList = com.alibaba.fastjson.JSON.parseArray(externalFleet, JSONObject.class);
		return jsonObjectList.stream().anyMatch(e -> {
			return e.getString("token").equals(token) && e.getString("source").equals(source);
		});
	}

	public Integer getType(HttpServletRequest request) {
		String token = request.getHeader("token");
		String source = request.getHeader("source");
		String externalFleet = dictionariesTDao.getListByDTableName("ExternalFleet");
		List<JSONObject> jsonObjectList = com.alibaba.fastjson.JSON.parseArray(externalFleet, JSONObject.class);
		List<Integer> collect = jsonObjectList.stream().filter(e -> {
			return e.getString("token").equals(token) && e.getString("source").equals(source);
		}).map(e -> e.getInteger("type")).collect(Collectors.toList());
		return collect.get(0);
	}

	/**
	 * 处理历史车队
	 *
	 * @return
	 */
	@RequestMapping(value = "/appFleetHistory.aspx", method = RequestMethod.GET)
	public BaseResponse appFleetHistory() {
		try {
			return cipFleetService.appFleetHistory();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}


	/**
	 * 处理历史车队
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateFleetListByUserId.aspx", method = RequestMethod.GET)
	public BaseResponse updateFleetListByUserId(@RequestParam("userId") Long userId) {
		try {
			 cipFleetService.updateFleetListByUserId(userId);
			return BaseResponse.success();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}

	/**
	 * 处理历史车队
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateFleetList.aspx", method = RequestMethod.GET)
	public BaseResponse updateFleetList() {
		try {
			cipFleetService.updateFleetList();
			return BaseResponse.success();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return BaseResponse.error("未知错误");
		}
	}

}
